//
//  QMAUIDelegateImp.m
//  QQMiniAppSDK
//
//  Created by raymonddeng on 2021/1/29.
//

#import "QMAUIDelegateImp.h"
#import "MBProgressHUD.h"
#import "MAShareView.h"
@interface QMAUIDelegateImp()
@property (nonatomic, strong) MBProgressHUD *hud;
@end

@implementation QMAUIDelegateImp

- (CGFloat)fitScreenH:(CGFloat)value {
    //TODO: 宿主可替换成按iphone6机型适配
    return value;
}

- (CGFloat)fitScreenW:(CGFloat)value {
    //TODO: 宿主可替换成按iphone6机型适配
    return value;
}

/// 展示loading
/// - Parameter info: loading 信息
- (void)showLoading:(QMALoadingInfo *)info {
    NSString *title = info.title;
    BOOL mask = info.mask;
    
    UIView *view = info.parentView;
    if(!view) {
        view = [UIApplication sharedApplication].keyWindow;
    }
    [self.hud removeFromSuperview];
    //TODO: 宿主可替换自己的样式
    self.hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;  // loading的mode转菊花
    self.hud.label.text = title;
    self.hud.userInteractionEnabled = mask;
    self.hud.removeFromSuperViewOnHide = YES;
    [self.hud showAnimated:YES];
}

/// 隐藏loading
- (void)hideLoading {
    [self.hud hideAnimated:YES];
    [self.hud removeFromSuperview];
}


/// 展示toast
/// - Parameters:
///   - infos: toast信息
///   - application: 小游戏实例信息
- (void)showToast:(QMAToastInfo *)infos application:(MABaseApplication *)application {
    __weak typeof(self) weakSelf = self;
    NSString *basePath = [application.package getPackagePath];
    dispatch_async(dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf) self = weakSelf;
        // block里不持有application,否则当app被释放之后再访问会导致crash
        if (self == nil) {
            return;
        }
        
        NSString *title = infos.title;
        QMAToastIconType icon = infos.iconType;
        NSString *image = infos.image;  // 自定义图标路径
        CGFloat duration = infos.duration;
        BOOL mask = infos.mask;
        
        UIView *view = [UIApplication sharedApplication].keyWindow;

        [self.hud removeFromSuperview];
        self.hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
        //设置title，image，icon等参数
        if (image.length > 0) {
            self.hud.mode = MBProgressHUDModeCustomView;
            UIImage *img = [UIImage imageWithContentsOfFile:[basePath stringByAppendingPathComponent:image]];
            self.hud.customView = [[UIImageView alloc] initWithImage:img];
            // 设置自定义图片
        } else if (icon == QMAToastIconTypeLoading) {
            // loading图标
            self.hud.mode = MBProgressHUDModeIndeterminate;
            // 设置标题
            self.hud.label.text = title;
        } else if (icon == QMAToastIconTypeSuccess) {
            // 默认图标，这里需要设置默认图标，客户端设置 给出图标之后加上 todo
            self.hud.mode = MBProgressHUDModeIndeterminate;
            // 设置标题
            self.hud.label.text = title;
        } else {
            self.hud.mode = MBProgressHUDModeText;
            self.hud.label.text = title;
        }
        
        // 设置是否可以点击
        self.hud.userInteractionEnabled = mask;
        self.hud.removeFromSuperViewOnHide = YES;
        self.hud.minShowTime = duration / 1000;
        [self.hud showAnimated:YES];
        [MBProgressHUD hideHUDForView:view animated:YES];
    });
}

/// 隐藏toast
- (void)hideToast {
    [self.hud hideAnimated:YES];
    [self.hud removeFromSuperview];
}

/// 展示actionSheet
- (void)showActionSheetWithTitle:(NSString *)title
               cancelButtonTitle:(NSString *)cancelButtonTitle
                    cancelAction:(dispatch_block_t)cancelAction
      otherButtonTitleAndActions:(NSArray *)otherButtonTitleAndActions
                    dismissBlock:(dispatch_block_t)dismissBlock
        presentingViewController:(UIViewController *)presentingViewController {
    // demo使用UIAlertController
    UIAlertController *alertCon = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    for (int i = 0; i < otherButtonTitleAndActions.count; i++) {
        QMASheetItemInfo *info = otherButtonTitleAndActions[i];
        UIAlertAction *shareAction = [UIAlertAction actionWithTitle:info.title ?: @"未设置 title"
                                                              style:UIAlertActionStyleDefault
                                                            handler:^(UIAlertAction *_Nonnull action) {
            void (^callback)(QMASheetActionParams *params) = info.action;
            callback ? callback(nil) : nil;
            // 一定要调用dismissblock
            if (dismissBlock) {
                dismissBlock();
            }
        }];
        [alertCon addAction:shareAction];
    }
    
    // 取消
    UIAlertAction *cancelBlock = [UIAlertAction actionWithTitle:cancelButtonTitle
                                                          style:UIAlertActionStyleCancel
                                                        handler:^(UIAlertAction *_Nonnull action) {
        if (cancelAction) {
            cancelAction();
        }
        // 一定要调用dismissblock
        if (dismissBlock) {
            dismissBlock();
        }
    }];
    [alertCon addAction:cancelBlock];
    
    // 展示的方式交给delegate来处理，比如是QUI，创建的actionsheet是一个UIView
    [presentingViewController presentViewController:alertCon animated:YES completion:nil];
}

/// 展示alert弹窗
- (void)showAlertWithTitle:(NSString *)title
               withMessage:(NSString *)message
              actionBlocks:(NSArray<AlertActionInfo *> *)actionTitleAndblocks
  presentingViewController:(UIViewController *)presentingViewController {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    for (NSInteger i = 0; i < actionTitleAndblocks.count; i++) {
        AlertActionInfo *info = actionTitleAndblocks[i];
        UIAlertAction *action = [UIAlertAction actionWithTitle:info.labelInfo
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction *_Nonnull action) {
            //MARK: 这里需要用actionCheckBlock
            if (info.actionCheckBlock) {
                info.actionCheckBlock(YES);
            }
        }];
        [alertVC addAction:action];
    }
    
    [presentingViewController presentViewController:alertVC animated:YES completion:nil];
}

/// 展示alert弹窗
- (void)showPopupWithTitle:(NSString *)title
                   message:(NSString *)message
              actionBlocks:(NSArray<AlertActionInfo *> *)actionTitleAndblocks
   isDismissWhenBackground:(BOOL)isDismissWhenBackground 
  presentingViewController:(UIViewController *)presentingViewController {
    [self showAlertWithTitle:title withMessage:message actionBlocks:actionTitleAndblocks presentingViewController:presentingViewController];
}

/// 收起弹窗
- (void)clearAllActionSheet {
    //TODO: 前面如果实现了自定义的ActionSheet, 在旋转时会调用此方法，如果需要收起，可实现该方法
}

/// 是否处于DarkMode模式
- (BOOL)isDarkMode {
    //TODO: 宿主可替换
    return false;
}

/// 点击右上角按钮，弹起更多视图界面
- (UIView *)showMoreButtonActionSheetWithApp:(MABaseApplication *)app
                           cancelButtonTitle:(nullable NSString *)cancelButtonTitle
                                cancelAction:(nullable dispatch_block_t)cancelAction
                  otherButtonTitleAndActions:(nullable NSArray *)otherButtonTitleAndActions
                                dismissBlock:(nullable dispatch_block_t)dismissBlock {
    
    MAShareView *shareView = [MAShareView new];
    shareView.autoRotate = NO;
    shareView.needBlurEffect = NO;
    shareView.dismissBlock = dismissBlock;
    shareView.cancelActionBlock = cancelAction;
    
    NSMutableArray<MAShareActivity *> *activityArray = [NSMutableArray array];
    for (QMASheetItemInfo *info in otherButtonTitleAndActions) {
        NSString *imageName = [self shareViewImageNameForType:info.type];
        if (imageName.length == 0 || info.title.length == 0) {
            continue;
        }
        
        MAShareActivity *activity = [MAShareActivity new];
        activity.title = [self shareViewItemTitleForType:info.type] ? : info.title;
        activity.actionBlock = ^{
            if (info.action) {
                info.action(nil);
            }
        };
        
        activity.icon = [UIImage imageNamed:imageName];
        [activityArray addObject:activity];
    }
    shareView.activityItems = activityArray;
    [shareView showInView:app.topViewController.view];
    
    return shareView;;
}

- (NSString *)shareViewImageNameForType:(MAUIDelegateShareViewType)type {
    static NSDictionary<NSNumber *, NSString *> *imageNameDict = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        imageNameDict = @{
            //TODO: 能力可选实现
            @(MAUIDelegateShareViewTypeFriend)              :   @"share_qqico",
            @(MAUIDelegateShareViewTypeQZone)               :   @"share_c",
            @(MAUIDelegateShareViewTypeWechatFriend)        :   @"share_w",
            @(MAUIDelegateShareViewTypeWechatMoment)        :   @"share_q",
//            @(MAUIDelegateShareViewTypeAbout)               :   @"about",
//            @(MAUIDelegateShareViewTypeComplaint)           :   @"report",
//            @(MAUIDelegateShareViewTypeSetting)             :   @"pushSetup",

//            @(MAUIDelegateShareViewTypeShortcut)            :   @"addToDesktop",
//            @(MAUIDelegateShareViewTypeHomePage)            :   @"restartApplet",
//            @(MAUIDelegateShareViewTypeDebug)               :   @"debug",
//            @(MAUIDelegateShareViewTypevConsoleLog)         :   @"debug",
//            @(MAUIDelegateShareViewTypePerformanceClose)    :   @"debug",
//            @(MAUIDelegateShareViewTypePerformanceOpen)     :   @"debug",
//            @(MAUIDelegateShareViewTypevConsoleClose)       :   @"debug",
//            @(MAUIDelegateShareViewTypevConsoleOpen)        :   @"debug",

        };
    });
    
    return imageNameDict[@(type)] ? : nil;
}

- (NSString *)shareViewItemTitleForType:(MAUIDelegateShareViewType)type {
    static NSDictionary<NSNumber *, NSString *> *titleDict = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        titleDict = @{
            //TODO: 能力可选实现
            @(MAUIDelegateShareViewTypeFriend)              :   @"QQ好友",
            @(MAUIDelegateShareViewTypeQZone)               :   @"QQ空间",
            @(MAUIDelegateShareViewTypeWechatFriend)        :   @"微信",
            @(MAUIDelegateShareViewTypeWechatMoment)        :   @"朋友圈",
            @(MAUIDelegateShareViewTypeAbout)               :   @"关于",
            @(MAUIDelegateShareViewTypeComplaint)           :   @"举报",
            @(MAUIDelegateShareViewTypeSetting)             :   @"设置",
            
//            @(MAUIDelegateShareViewTypeShortcut)            :   @"添加到桌面",
//            @(MAUIDelegateShareViewTypeHomePage)            :   @"重启小程序",
//            @(MAUIDelegateShareViewTypeDebug)               :   @"打开调试",
//            @(MAUIDelegateShareViewTypevConsoleLog)         :   @"导出vconsole",
//            @(MAUIDelegateShareViewTypePerformanceClose)    :   @"关性能窗口",
//            @(MAUIDelegateShareViewTypePerformanceOpen)     :   @"开性能窗口",
//            @(MAUIDelegateShareViewTypevConsoleClose)       :   @"关闭调试",
//            @(MAUIDelegateShareViewTypevConsoleOpen)        :   @"打开调试",
        };
    });
    
    return titleDict[@(type)] ? : nil;
}


@end
